<?php
class Goodsproviderseller extends CS_Controller
{
    private $uidArray = array();
    private $priceProfit = array();
    function _init()
    {
        $this->load->helper('profit');
        $this->load->library('pagination');
        $this->load->model('goods_provider_seller_model', 'goods_provider_seller');
        $this->load->model('user_model', 'user');
        $this->load->model('user_type_model', 'user_type');
        $this->load->model('goods_map_profit_model', 'goods_map_profit');
        $this->load->model('scenery_base_model', 'scenery_base');
        $this->load->model('goods_base_model', 'goods_base');
        $this->load->model('scenery_good_category_model', 'scenery_good_category');
        $this->load->model('operate_power_log_model', 'operate_power_log');
    }
    
    public function index($pg = 1)
    {
        $excel = $this->input->get('excel');
        if (!empty($excel) && $excel== 'excel') {
            $this->excelExport();
        } else {
            $goods_id = $this->input->get('goods_id');
            if (empty($goods_id)) {
                $this->error('goodsproviderseller/index', $this->input->get(), '门票信息有误');
            }
            $page_num = 20;
            $num = ($pg - 1) * $page_num;
            $config['first_url'] = base_url('goodsbase/index').$this->pageGetParam($this->input->get()); //goods_id 必带
            $config['suffix'] = $this->pageGetParam($this->input->get());
            $config['base_url'] = base_url('goodsproviderseller/index');
            $config['total_rows'] = $this->goods_provider_seller->total($this->input->get());
            $config['uri_segment'] = 3;
            $this->pagination->initialize($config);
            $data['pg_list']   = $this->pagination->create_links();
            $data['page_list'] = $this->goods_provider_seller->page_list($page_num, $num, $this->input->get());
            $data['all_rows']  = $config['total_rows'];
            $data['pg_now']    = $pg;
            $data['pid'] = array(1=>'购买者付', 2=>'供应商付', 3=>'二级供应商付');
            $data['bit_source'] = $this->scenery_good_category->find(true);
            $this->load->view('goodsproviderseller/index', $data);
        }
    }
    
    /**
     * 批量删除议价功能
     */
    public function batchDelete()
    {
        $ids = $this->input->post('ids');
        if (empty($ids)) {
            $this->jsonMessage('未选择需删除的议价');
        }
        $this->db->trans_start();
        $is_delete = $this->goods_provider_seller->batchDelete($ids);
        $this->operate_power_log->insertOperatePowerLog(array('uid'=>$this->uid,'name'=>$this->name,'record'=>'操作删除编号'.implode(',', $ids).'类：'.__CLASS__.'-方法：'.__FUNCTION__, 'content'=>json_encode($this->input->post())));
        $this->db->trans_complete();
        if ($is_delete) {
            $this->jsonMessage('', base_url('goodsproviderseller/index').'?goods_id='.$this->input->post('goods_id'));
        } else {
            $this->jsonMessage('删除失败！');
        }
    }
    
    public function add()
    {
        $sid = $this->input->get('sid');
        $result = $this->scenery_base->findById($sid);
        if ($result->num_rows() <= 0) {
            $this->error('goodsbase/index', $this->input->get(), '景区信息有误');
        }
        $data['sceneryBase'] = $result->row();
        $goods_id = $this->input->get('goods_id');
        $result1 = $this->goods_base->findById($goods_id);
        if ($result1->num_rows() <= 0) {
            $this->error('goodsproviderseller/index', $this->input->get(), '门票信息有误');
        }
        $data['goodsBase'] = $result1->row();
        $data['userType'] = $this->user_type->get_list();
        $this->load->view('goodsproviderseller/add', $data);
    }
    
    public function ajaxValidate()
    {
        if (!$this->input->post('id')) { //添加时
            //是否存在这些用户
            $error = $this->validateUserName();
            if (!empty($error)) {
                $this->jsen($error);
            }
    
            //验证这些用户是否议过价
            $error = $this->validateSeller();
            if (!empty($error)) { //如果不为空，则此用户议过价
                $this->jsen($error);
            }
        }
        //验证数据的正确性
        $error = $this->validataPostInfo();
        if (!empty($error)) {
            $this->jsen($error);
        }
        
        //存在议价ID  表示是编辑   不存在是添加议价
        if ($this->input->post('id')) {//议价ID
            $this->editPost();
        } else {
            $this->addPost();
        }
    }
    
    public function addPost()
    {
        $this->db->trans_start();
        foreach ($this->uidArray as $value) {
            $goodsId = $this->goods_provider_seller->add($this->input->post(), $value);// 议价添加
            //$resultId = $this->goods_map_profit->insertGoodsMapProfit($this->input->post(), $goodsId);//分润添加
        }
        $this->operate_power_log->insertOperatePowerLog(array('uid'=>$this->uid,'name'=>$this->name,'record'=>'操作类：'.__CLASS__.'-方法：'.__FUNCTION__, 'content'=>json_encode($this->input->post())));
        $this->db->trans_complete();
        if ($this->db->trans_status() === TRUE) {
            $this->session->set_flashdata('success', '添加成功！');
            $this->jsen('goodsproviderseller/index?sid='.$this->input->post('sid').'&goods_id='.$this->input->post('goods_id'), true);
        } else {
            $this->session->set_flashdata('error', '添加失败！');
            $this->jsen('goodsproviderseller/index?sid='.$this->input->post('sid').'&goods_id='.$this->input->post('goods_id'), true);
        }
    }
    
    public function edit($id)
    {
        $sid = $this->input->get('sid');
        $result = $this->scenery_base->findById($sid);
        if ($result->num_rows() <= 0) {
            $this->error('goodsbase/index', $this->input->get(), '景区信息有误');
        }
        $data['sceneryBase'] = $result->row();
        $goods_id = $this->input->get('goods_id');
        $result1 = $this->goods_base->findById($goods_id);
        if ($result1->num_rows() <= 0) {
            $this->error('goodsproviderseller/index', $this->input->get(), '门票信息有误');
        }
        $data['goodsBase'] = $result1->row();
        $data['userType'] = $this->user_type->get_list();
        $data['row'] = $this->goods_provider_seller->findById($id);
        $this->load->view('goodsproviderseller/edit', $data);
    }
    
    public function editPost()
    {
        $this->db->trans_start();
        $lineBargainingId = $this->goods_provider_seller->update($this->input->post());// 议价添加
        //$is_delete = $this->goods_map_profit->delete($this->input->post('goods_id'), 'bargaining');
        //$resultId = $this->goods_map_profit->add($this->input->post());//分润添加
        $this->operate_power_log->insertOperatePowerLog(array('uid'=>$this->uid,'name'=>$this->name,'record'=>'操作类：'.__CLASS__.'-方法：'.__FUNCTION__, 'content'=>json_encode($this->input->post())));
        $this->db->trans_complete();
        if ($this->db->trans_status() === FALSE) {
            $this->session->set_flashdata('error', '保存失败！');
            $this->jsen('goodsproviderseller/index?sid='.$this->input->post('sid').'&goods_id='.$this->input->post('goods_id'), true);
        } else {
            $this->session->set_flashdata('success', '保存成功！');
            $this->jsen('goodsproviderseller/index?sid='.$this->input->post('sid').'&goods_id='.$this->input->post('goods_id'), true);
        }
    }
    
    public function delete($id)
    {
        $this->db->trans_start();
        $is_delete = $this->goods_provider_seller->delete($id);
        //$resultId  = $this->goods_map_profit->delete($id, 'bargaining');
        $this->operate_power_log->insertOperatePowerLog(array('uid'=>$this->uid,'name'=>$this->name,'record'=>'操作删除编号'.$id.'类：'.__CLASS__.'-方法：'.__FUNCTION__, 'content'=>json_encode($this->input->post())));
        $this->db->trans_complete();
        if ($is_delete) {
            $this->success('goodsproviderseller/index', array('sid'=>$this->input->get('sid'), 'goods_id'=>$this->input->get('goods_id')), '删除成功！');
        } else {
            $this->error('goodsproviderseller/index', array('sid'=>$this->input->get('sid'), 'goods_id'=>$this->input->get('goods_id')), '删除失败！');
        }
    }
    
    private function jsen($error, $flag=false)
    {
        if (is_array($error)) {
            $erro = '';
            foreach ($error as $er) {
                $erro .= '<p>'. $er . '</p>';
            }
            $error = $erro;
        }
        echo json_encode(array(
            'status'   => $flag,
            'messages' => $error
        ));exit;
    }

    public function validateUserName()
    {
        $error = array();
        $seller_name = trim(strtr($this->input->post('user_name'), array('，'=>',')), ',');
        if (strpos($seller_name, ',') === false) {
            $sellerArray = array($seller_name);
        } else {
            $sellerArray = explode(',', $seller_name);
        }
        if (empty($sellerArray)) {
            return $error[] = '分销商不可为空！';
        }
        $resultUtitSeller = $this->user->findByIds(array('user_name'=>$sellerArray, 'user_type'=>UTID_SELLER)); //用户类型为分销商
        if ($resultUtitSeller->num_rows() <= 0) {
            return $error[] = implode($sellerArray, ',').'分销商用户不存在！';
        }
    
        $sellerQuery = array();
        foreach ($resultUtitSeller->result() as $item) {
            $sellerQuery[$item->uid] = $item->user_name;
        }
        
        $diffArray = array_diff($sellerArray, $sellerQuery);
        if (!empty($diffArray)) {
            return $error[] = '分销商为 "'.implode($diffArray, ',').'" 的用户不存在';
        }
    
        $this->uidArray = array_flip($sellerQuery);  //key和值交换
        return $error;
    }
    
    public function validateSeller()
    {
        $error = array();
        $goodsId = $this->input->post('goods_id');
        if (!$goodsId) {
            return $error[] = '价格有错误，请重新议价.';
        }
        $result = $this->goods_provider_seller->findByArray(array('goods_id'=>$goodsId, 'seller_id'=>$this->uidArray));
        $userName = array();
        if ($result->num_rows() > 0) {
            foreach ($result->result() as $value) {
                $name = array_search($value->seller_id, $this->uidArray);
                if ($name) {
                    $userName[] = $name;
                }
            }
        }
        if (!empty($userName)) {
            $error[] = '用户 "'.implode(',', $userName).'" 已经议过价了.';
            $error[] = '分销商为'.implode(array_diff(array_keys($this->uidArray), $userName), ',').'的用户已存在';
        }
        return $error;
    }
    
    public function validataPostInfo()
    {
        $error = array();
        if (!is_numeric($this->input->post('market_price'))) {
            $error[] = '在线销售价不可为空，只能为数字。';
        }
        if (!is_numeric($this->input->post('provide_price'))) {
            $error[] = '结算价不可为空，只能为数字。';
        }
        if (!is_numeric($this->input->post('poundage'))) {
            $error[] = '总手续费不可为空，只能为数字。';
        }
        
        $market_price = $this->input->post('market_price');
        $scen_price = $this->input->post('scen_price');
        $poundage = $this->input->post('poundage');
        $provide_price = $this->input->post('provide_price')+$poundage;
        if (($market_price < $provide_price) || $market_price < $provide_price) {
            $error[] = '在线销售价或者景区到付价必须要大于等于供应价+手续费。';
        }
        
        $prosecond_profit = $this->input->post('prosecond_profit'); //二级供应商利润
        $beizhu_profit = $this->input->post('beizhu_profit'); //着想手续费
        $purchaser_profit = $this->input->post('purchaser_profit'); //采购省代手续费
        $city_profit = $this->input->post('city_profit'); //采购省市代手续费
        $manager_l1_profit = $this->input->post('manager_l1_profit'); //分销省代手续费
        $manager_l2_profit = $this->input->post('manager_l2_profit'); //分销市代手续费
        
        $poundageTotal = $prosecond_profit + $beizhu_profit + $purchaser_profit + $city_profit + $manager_l1_profit + $manager_l2_profit;
        if (bccomp($poundageTotal, $poundage, 3) != 0) {
            $error[] = '分润总和（'.$poundageTotal.'）不等于手续费（'.$poundage.'）。';
        }
        
        $prosecond_id = $this->input->post('prosecond_id');
        if (!empty($prosecond_id)) {//二级供应商用户必须为分销商
            $result = $this->user->findByIds(array('uid'=>$prosecond_id, 'user_type'=>UTID_SELLER));
            if ($result->num_rows() <= 0) {
                $error[] = '二级供应商用户uid('.$prosecond_id.')不存在！';
            }
        }
        return $error;
    }
    
    public function excelExport()
    {
        $getData = $this->input->get();
        if (!empty($getData['excel'])) {
            unset($getData['excel']);
        }
        $result = $this->goods_provider_seller->excelExport($this->input->get());
        if ($result->num_rows() <= 0) {
            $this->error('goodsproviderseller/index', $getData, '没有数据可以导出');
        }
        if ($result->num_rows() > 10000) {
            $this->error('goodsproviderseller/index', $getData, '由于导出的数据太多，请添加其它搜索条件');
        }
        $arrayOrder = $result->result_array();
    
        array_unshift($arrayOrder, array('供应商编号', '分销商帐号', '分销商编号', '门票编号', '在线销售价', '景区到付价', '供应价', '手续费', '银行手续费', '二级供应商编号', '二级供应商利润', '结算方式(1:系统 2:自主)', '手续费支付方式(1:2:3:)', '着想利润', '采购省代编号', '采购省代利润', '采购市代编号', '采购市代利润', '分销省代编号', '分销省代手续费', '分销市代编号', '分销市代手续费', '来源'));
        $this->load->library('excel');
        $this->excel->addArray($arrayOrder);
        $this->excel->generateXML(date('Ymd').'-'.$this->input->get('goods_id'));
    }
}